<template>
  <div class="map duck-man duck-content">
    <dm-map />
  </div>
  <div class="duck-man duck-content">
    <h5>参数归一化</h5>
  </div>
  <div class="duck-man duck-content">
    <p lang="digit">0123456789</p>
  </div>
</template>

<script setup lang="ts">
  import dmMap from '@/components/dmMap/index.vue'

  interface DateInfo {
    yyyy: string
    MM: string
    dd: string
    HH: string
    mm: string
    ss: string
    ms: string
  }

  type FormatterString = 'date' | 'datetime'

  const formateDate = (date: Date, formatter: FormatterString | Function, isPad: boolean = false) => {
    formatter = _formatterNormalize(formatter)!
    const info = {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      date: date.getDate(),
      hours: date.getHours(),
      minutes: date.getMinutes(),
      seconds: date.getSeconds(),
      milliseconds: date.getMilliseconds()
    }

    const dateInfo: DateInfo = {
      yyyy: '',
      MM: '',
      dd: '',
      HH: '',
      mm: '',
      ss: '',
      ms: ''
    }
    dateInfo.yyyy = isPad ? info.year.toString().padStart(4, '0') : info.year
    dateInfo.MM = isPad ? info.month.toString().padStart(2, '0') : info.month
    dateInfo.dd = isPad ? info.date.toString().padStart(2, '0') : info.date
    dateInfo.HH = isPad ? info.hours.toString().padStart(2, '0') : info.hours
    dateInfo.mm = isPad ? info.minutes.toString().padStart(2, '0') : info.minutes
    dateInfo.ss = isPad ? info.seconds.toString().padStart(2, '0') : info.seconds
    dateInfo.ms = isPad ? info.milliseconds.toString().padStart(3, '0') : info.milliseconds

    return formatter(dateInfo)
  }

  const _formatterNormalize = (formatter: string | Function) => {
    if (typeof formatter === 'function') {
      return formatter
    }
    if (typeof formatter !== 'string') {
      throw new TypeError('formatter must be string or function')
    }
    if (formatter === 'date') {
      formatter = 'yyyy-MM-dd'
    } else if (formatter === 'datetime') {
      formatter = 'yyyy-MM-dd HH:mm:ss'
    }

    return (dateInfo) => {
      const { yyyy, MM, dd, HH, mm, ss, ms } = dateInfo

      if (typeof formatter === 'string') {
        return formatter
          .replace('yyyy', yyyy)
          .replace('MM', MM)
          .replace('dd', dd)
          .replace('HH', HH)
          .replace('mm', mm)
          .replace('ss', ss)
          .replace('ms', ms)
      }
    }
  }

  const res = formateDate(new Date(), 'date')
  console.log('%c [ res ]-86', 'font-size:13px; background:#9f5eae; color:#e3a2f2;', res)
</script>

<style lang="less" scoped></style>
